package org.dizena.base.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JwtUtil
{
    private static final long EXPIRE_TIME = 60L * 24 * 3600 * 1000;

    public static boolean verify(String token, String account, String password)
    {
        try
        {
            Algorithm algorithm = Algorithm.HMAC256(password);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("account", account).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }
        catch (Exception exception)
        {
            return false;
        }
    }

    public static String getAccount(String token)
    {
        try
        {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("account").asString();
        }
        catch (JWTDecodeException e)
        {
            return null;
        }
    }

    public static String sign(String account, String password)
    {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(password);
        // 附带account信息
        return JWT.create().withClaim("account", account).withExpiresAt(date).sign(algorithm);
    }

}
